import { Component } from '@angular/core';


const todos = [
  {id:1, title:'吃饭', done:true},
  {id:2, title:'睡觉', done:true},
  {id:3, title:'Code', done:true},
  {id:4, title:'看动画片', done:true},
  {id:5, title:'玩游戏', done:true},
  
];

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  public todos:{
    id:number
    title:string
    done:boolean
  }[] = JSON.parse(window.localStorage.getItem('todos') || '[]')


  
  // 一个属性，存储当前点击链接的标识，有三种状态， all, active, completed
  public visibility:string = 'all';

  public currentEditing:{
    id:number,
    title:string,
    done:boolean
  } = null

  // 根据visibility属性，返回过滤后的数据
  
  get filterTodos(){
    if(this.visibility === 'all'){
      return this.todos
    }else if(this.visibility === 'active'){
      return this.todos.filter(t => !t.done)
    }else if(this.visibility === 'completed'){
      return this.todos.filter(t => t.done)
    }
  }

  
  ngOnInit(){
    // onhashchange为当锚点改变时，获取链接
    // 调用该方法，当刷新网页时，之前todo列表的状态也能保持住
    this.hashChangeHandler();
    window.onhashchange = this.hashChangeHandler.bind(this)
  }

  ngDoCheck(){
    window.localStorage.setItem('todos', JSON.stringify(this.todos))
  }



  hashChangeHandler():void{
    
    const hash = window.location.hash.substr(1)
      switch(hash)
      {
        case '/':
          this.visibility = 'all';
          break;
        case '/completed':
          this.visibility = 'completed';
          break;
        case '/active':
          this.visibility = 'active';
          break;
      }
  }


  addTodo(e):void{
    const titleText = e.target.value;
    if(!(titleText.length > 0))
    {
      return;
    }
    let todo = todos[todos.length - 1]
    this.todos.push({
      id: todo? todo.id : 1,
      title: titleText,
      done: false
    })
    //清除文本框的内容
    e.target.value = "";

  }

  removeTodo(index:number):void{
    this.todos.splice(index,1)
  }

  saveEdit(todo, e):void{
    // 赋值
    todo.title = e.target.value;
    //使其失去焦点
    this.currentEditing = null;
  }

  handleEditKeyUp(e):void{
    //取消编辑
    e.target.value = this.currentEditing.title
    this.currentEditing = null;
  }

  clearAllDone():void{
    this.todos = this.todos.filter(t=>!t.done)
  }


  get toggleAll(){
    return this.todos.every(t => t.done)
  }

  set toggleAll(val){
    this.todos.forEach(t=>t.done = val)
  }

  get remaningCount(){
    return this.todos.filter(t => !t.done).length
  }
  
}
